import React, { useEffect, useState } from 'react';
import { Button, Card, Image, Tag, Skeleton, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import { TvSeriesInfo, TV_SERIES_STATUS, TV_SERIES_TYPE, getTvSeriesInfo } from '@/services/TvSeriesInfo';
import styles from './detail.less';

const DramaDetail: React.FC = () => {
  const { idBase64 } = useParams<{ idBase64: string }>();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<TvSeriesInfo | null>(null);
  const [isHorizontal, setIsHorizontal] = useState(false);

  // 获取详情数据
  useEffect(() => {
    const fetchData = async () => {
      console.log(idBase64);
      if (!idBase64) return;
      try {
        // base64解码
        const id = atob(idBase64);
        console.log(id);
        setLoading(true);
        const response = await getTvSeriesInfo(parseInt(id));
        setData(response);
      } catch (error) {
        message.error('获取影视详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [idBase64]);

  // 处理返回列表
  const handleBack = () => {
    history.back();
  };

  // 处理图片加载完成
  const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    const img = e.target as HTMLImageElement;
    setIsHorizontal(img.naturalWidth > img.naturalHeight);
  };

  // 处理字符串分割
  const splitString = (str?: string) => {
    if (!str) return [];
    return str
      .replace(/，/g, ',')
      .replace(/、/g, ',')
      .replace(/;/g, ',')
      .replace(/；/g, ',')
      .split(',')
      .map(item => item.trim())
      .filter(Boolean);
  };

  // 基本信息展示
  const BasicInfo = () => {
    if (!data) return null;

    return (
      <div className={styles.infoGrid}>
        <div className={styles.infoItem}>
          <span className={styles.label}>影视类型</span>
          <span className={styles.value}>
            <Tag color="blue">
              {TV_SERIES_TYPE[data.type as keyof typeof TV_SERIES_TYPE]?.label || '未知'}
            </Tag>
          </span>
        </div>

        <div className={styles.infoItem}>
          <span className={styles.label}>状态</span>
          <span className={styles.value}>
            <Tag color={
              data.status === 'WAITING_PLAY' ? 'orange' :
                data.status === 'PLAYING' ? 'green' :
                  data.status === 'FINISHED' ? 'blue' : 'default'
            }>
              {TV_SERIES_STATUS[data.status as keyof typeof TV_SERIES_STATUS]?.label || '未知'}
            </Tag>
          </span>
        </div>

        <div className={styles.infoItem}>
          <span className={styles.label}>导演</span>
          <span className={styles.value}>{data.director || '未知'}</span>
        </div>

        <div className={styles.infoItem}>
          <span className={styles.label}>语言</span>
          <span className={styles.value}>{data.language || '未知'}</span>
        </div>

        <div className={styles.infoItem}>
          <span className={styles.label}>总集数</span>
          <span className={styles.value}>{data.numberOfEpisodes || '未知'}</span>
        </div>

        <div className={styles.infoItem}>
          <span className={styles.label}>首播日期</span>
          <span className={styles.value}>{data.releaseDate || '未知'}</span>
        </div>

        <div className={styles.infoItem}>
          <span className={styles.label}>类型</span>
          <span className={styles.value}>
            <div className={styles.tagList}>
              {splitString(data.genre).map((item, index) => (
                <Tag key={index} color="blue">{item}</Tag>
              ))}
            </div>
          </span>
        </div>

        <div className={styles.infoItem}>
          <span className={styles.label}>饰演角色</span>
          <span className={styles.value}>
            <div className={styles.tagList}>
              {splitString(data.playRole).map((item, index) => (
                <Tag key={index} color="green">{item}</Tag>
              ))}
            </div>
          </span>
        </div>
      </div>
    );
  };

  // 简介部分
  const Description = () => {
    if (!data?.description) return null;

    return (
      <div className={styles.description}>
        <div className={styles.label}>简介</div>
        <div className={styles.value}>{data.description}</div>
      </div>
    );
  };

  // 播放源列表
  const PlaySourceList = () => {
    if (!data) return null;

    return (
      <div className={styles.playSourceSection}>
        <h3 className={styles.sectionTitle}>播放源</h3>
        <div className={styles.sourceList}>
          {data.playSourceInfo?.length ? (
            data.playSourceInfo.map((source, index) => (
              <a
                key={index}
                href={source.sourceUrl}
                target="_blank"
                rel="noopener noreferrer"
                className={styles.sourceItem}
              >
                {source.sourceName}
              </a>
            ))
          ) : (
            <div className={styles.emptySource}>暂无播放源</div>
          )}
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className={styles.container}>
        <Card bodyStyle={{ padding: '16px' }}>
          <Skeleton active paragraph={{ rows: 10 }} />
        </Card>
      </div>
    );
  }

  if (!data) {
    return (
      <div className={styles.container}>
        <Card bodyStyle={{ padding: '16px' }}>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <h3>未找到影视信息</h3>
            <Button
              type="link"
              icon={<ArrowLeftOutlined />}
              onClick={handleBack}
            >
              返回
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <Card >
        <div className={styles.pageHeader}>
          <Button
            type="link"
            icon={<ArrowLeftOutlined />}
            onClick={handleBack}
            style={{ marginLeft: '-20px' }}
          >
            返回
          </Button>
          <h2 style={{ marginTop: '10px'}}>{data.title}</h2>
        </div>

        <div className={`${styles.content} ${isHorizontal ? styles.horizontal : ''}`}>
          
          <div className={styles.mainContent}>
            <div className={styles.posterSection}>
              {data.poster && (
                <div className={styles.posterWrapper}>
                  <Image
                    src={`/api/file/play/${data.poster}`}
                    alt="海报"
                    className={styles.poster}
                    onLoad={handleImageLoad}
                  />
                </div>
              )}
            </div>
            <div className={styles.basicInfo}>
              <BasicInfo />
            </div>
          </div>
          <Description />
          <PlaySourceList />
        </div>
      </Card>
    </div>
  );
};

export default DramaDetail; 